/**
 * 
 * */

bool Encrypt(const char *data, char *outEncryptedData, unsigned int nDataLength)
{
	char Key[256] = {0};
	snprintf(Key, sizeof(Key) - 1, "%s", FDFS_RC4_KEY);

	return rc4_Encrypt(Key, data, outEncryptedData, nDataLength);
}
bool Decrypt(const char *EncryptedData, char *outDecryptedData, unsigned int nDataLength)
{
	char Key[256] = {0};
	snprintf(Key, sizeof(Key) - 1, "%s", FDFS_RC4_KEY);

	return rc4_Decrypt(Key, EncryptedData, outDecryptedData, nDataLength);
}

bool Encrypt_Server(const char *data, char *outEncryptedData, unsigned int nDataLength)
{
	char Key[256] = {0};
	snprintf(Key, sizeof(Key) - 1, "%s", FDFS_RC4_KEY_SERVER);

	return rc4_Encrypt(Key, data, outEncryptedData, nDataLength);
}
bool Decrypt_Server(const char *EncryptedData, char *outDecryptedData, unsigned int nDataLength)
{
	char Key[256] = {0};
	snprintf(Key, sizeof(Key) - 1, "%s", FDFS_RC4_KEY_SERVER);

	return rc4_Decrypt(Key, EncryptedData, outDecryptedData, nDataLength);
}

bool rc4_Encrypt(const char *Key, const char *data, char *outEncryptedData, unsigned int nDataLength)
{
	int nKeyLength = strlen(Key);
	if (nDataLength > 0 && nKeyLength > 0)
	{
		unsigned char sBox[256] = {0};
		memset(outEncryptedData, 0, nDataLength);
		memcpy(outEncryptedData, data, nDataLength);

		rc4_init(sBox, (unsigned char *)Key, nKeyLength);
		rc4_crypt(sBox, (unsigned char *)outEncryptedData, nDataLength);

		return true;
	}
	return false;
}

bool rc4_Decrypt(const char *Key, const char *EncryptedData, char *outDecryptedData, unsigned int nDataLength)
{
	int nKeyLength = strlen(Key);
	if (nDataLength > 0 && nKeyLength > 0)
	{
		unsigned char sBox[256] = {0};
		memset(outDecryptedData, 0, nDataLength);
		memcpy(outDecryptedData, EncryptedData, nDataLength);

		rc4_init(sBox, (unsigned char *)Key, nKeyLength);
		rc4_crypt(sBox, (unsigned char *)outDecryptedData, nDataLength);

		return true;
	}
	return false;
}
/*初始化函数*/
void rc4_init(unsigned char *s, unsigned char *key, unsigned long keyLen)
{
	unsigned int i, j, k;
	unsigned char a;

	for (i = 0; i < 256; i++)
	{
		s[i] = (unsigned char)i;
	}

	j = k = 0;

	for (i = 0; i < 256; i++)
	{
		a = s[i];
		j = (unsigned char)(j + a + key[k]);
		s[i] = s[j];
		s[j] = a;
		if (++k >= keyLen)
		{
			k = 0;
		}
	}
}

void rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long dataLen)
{
	unsigned int i, x, y;
	unsigned char a, b;

	x = 0;
	y = 0;

	for (i = 0; i < dataLen; i++)
	{
		x = (unsigned char)(x + 1);
		a = s[x];
		y = (unsigned char)(y + a);
		s[x] = b = s[y];
		s[y] = a;
		Data[i] ^= s[(unsigned char)(a + b)];
	}
}